package org.base23.order.authentication.handler.resourceapi.login;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.base23.commons.utils.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

public class LoginInfoFilter extends OncePerRequestFilter {

  private static final Logger logger = LoggerFactory.getLogger(LoginInfoFilter.class);

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {
    logger.debug("Use LoginInfoFilter");

    String userInfo = request.getHeader("user");

    LoginAuthentication authentication = new LoginAuthentication();
    authentication.setUserInfo(userInfo);
    authentication.setAuthenticated(StringUtils.hasText(userInfo)); // 设置true，认证通过。
    if (StringUtils.hasText(userInfo)) {
      authentication.setCurrentUser(JSON.parseToMap(userInfo));
    }

    // 认证通过后，一定要设置到SecurityContextHolder里面去。
    SecurityContextHolder.getContext().setAuthentication(authentication);


    // 放行
    filterChain.doFilter(request, response);
  }
}
